import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormDynamicEntity } from 'src/app/base/form/dynamic/form.dynamic';
import { FormDynamicDropdownService } from 'src/app/base/form/dynamic/form.dynamic.dropdown.service';
import { FormDynamicTextboxService } from 'src/app/base/form/dynamic/form.dynamic.textbox.service';
import { FormDynamicService } from 'src/app/base/form/dynamic/form.dynamic.service';
import { NzMessageService } from 'ng-zorro-antd';
import { GisAttributeSearchUtils } from 'src/app/base/gis/search/gis.attribute.search';

declare var form: any;

@Component({
  selector: 'dynamic-attribute-find',
  templateUrl: './dynamic.component.html',
  styleUrls: ['./dynamic.component.scss'],
})

// 动态属性查询
export class MapDynamicAttributeComponent implements OnInit {


  // 图层字典
  layerDic: any;
  // 属性查询配置服务
  fs: any;
  // 属性查询查询参数
  paras = {
    type: '', baseUrl: '', layerName: '', inExtent: false,
    extent: {}, geometryField: ''
  };
  // 属性查询工具服务
  searchService: any;
  // 当前选中的图层节点对象
  node: any;
  // 当前选中的图层id
  layerId: string;
  // 属性查询字段
  filterFields: any;
  // 属性查询表单对象
  filterFroms: any;
  // 表头字段
  titleFields: [];
  // 内容字段
  contentFields: [];
  // 弹窗显示字段
  showFields: [];
  // 是否在视野范围内
  inExtent = false;
  // 动态表单对象
  @Input() form: FormGroup;
  // 存放级联下拉数据
  cascadeData: any;
  // 级联一级pid
  firstCascadePid: string;
  // 需要强制等于的类型
  equalTyle = ['INT', 'BOOLEAN', 'DOUBLE', 'FLOAT', 'LONG'];

  constructor(public fds: FormDynamicService, private msg: NzMessageService) {
    // 属性查询配置字典服务
    this.layerDic = new form.DictionaryService('g_attribute_config', this.filter);
    // 首结点不展开
    this.layerDic.expandFirst = false;
    // 禁用除尾结点之外的结点
    this.layerDic.disabledNoLeaf = true;

    // 属性查询配置表单服务
    this.fs = new form.FormTreeService('gisattributeconfig', {
      orderObject: { order: 0 },
      keyField: 'id',
      randomFields: ['id'],
      pageSize: 1000
    });

    // 属性查询工具服务
    this.searchService = new GisAttributeSearchUtils(this.msg);

    // 重新设置回调函数实例
    // this.searchService.option.clickEvent = (o, event) => {
    //   this.searchService.clickEventBack(o, event);
    //   alert("回调成功");
    // };
    // this.searchService.option.back = (ower) => {
    //   this.searchService.searchSuccessBack(ower);
    //   alert("回调成功");
    // };

  }

  ngOnInit(): void {
  }

  // 过滤掉不可用不显示的数据
  filter(data) {
    if (data) {
      const ri = [];
      for (let i = data.length - 1; i >= 0; i--) {
        const e = data[i];
        if (e.valid === false) {
          ri.push(i);
        }
        if (e.other.show === false || e.other.show === null) {
          ri.push(i);
        }
        if (e.info === '2' || e.info === '3') {
          ri.push(i);
        }
      }
      ri.forEach((j) => {
        data.splice(j, 1);
      });
      return data;
    }
  }

  /**
   * 数据变化监听事件
   */
  onChange(e: any) {
    this.searchService.change();
    // 查询选中配置
    if (!e) {
      this.initForm(null);
      return;
    }


    this.initForm(null);
    this.fs.defaultQueryObject = { id: e };
    this.fs.loadData(true, (datas) => {
      if (datas && datas[0]) {
        this.node = datas[0];
        this.initForm(this.node);
      }
    });
  }

  /**
   * 初始化表单对象
   */
  initForm(node: any) {

    this.titleFields = node && node.titleField ? node.titleField : [];
    this.contentFields = node && node.contentField ? node.contentField : [];
    this.showFields = node && node.showField ? node.showField : [];
    this.filterFields = node && node.filterField ? node.filterField : [];
    this.filterFroms = this.getFomDatas(this.filterFields);
    this.form = this.fds.toFormGroup(this.filterFroms);

    this.clearFormValue();
  }


  /**
   *  动态设置表单对象
   */
  getFomDatas(filterFields: any[]): Array<any> {
    const tempForms = [];

    // 级别
    let leavel = 1;
    // 所在分组
    let group;
    // 存储上一级key
    let tempKey = '';
    this.cascadeData = {};

    for (const field of filterFields) {
      let formDynamicEntity = new FormDynamicEntity<string>();
      formDynamicEntity.label = field.aliasName;

      if (this.equalTyle.includes(field.dataType)) {
        formDynamicEntity.key = field.name + ':=';
      } else {
        formDynamicEntity.key = field.dictionaryName ? field.name + ':=' : field.name;
      }

      formDynamicEntity.order = field.order;
      formDynamicEntity.placeholder = field.aliasName;

      if (field.dictionaryName && field.dictionaryName !== '') {
        // 如果该查询条件字段是字典
        formDynamicEntity.dictionaryName = field.dictionaryName;
        formDynamicEntity.dictionaryService = new form.DictionaryService(field.dictionaryName);
        formDynamicEntity.type = field.group ? 'cascade' : 'ordinary';
        if(field.dictionaryName === 'DI_LEI' || field.dictionaryName === 'LIN_ZHONG'){
          formDynamicEntity.type = 'tree'
        }
        // 处理级联数据
        if (formDynamicEntity.type === 'cascade') {
          if (field.group !== group) {
            group = field.group;
            leavel = 1;
          } else {
            leavel++;
          }
          if (leavel === 1) {
            this.cascadeData[formDynamicEntity.key] = { leavel, pid: field.dictionaryDataPid };
            this.firstCascadePid = field.dictionaryDataPid;
          } else {
            this.cascadeData[tempKey]['clear'] = formDynamicEntity.key;
            this.cascadeData[formDynamicEntity.key] = { leavel };
            this.cascadeData[formDynamicEntity.key]['load'] = tempKey;
          }
          tempKey = formDynamicEntity.key;
        }

        formDynamicEntity = new FormDynamicDropdownService(formDynamicEntity);
        formDynamicEntity.dictionaryService.expandFirst = false;//不展开第一列
      } else {
        formDynamicEntity = new FormDynamicTextboxService(formDynamicEntity);
      }

      tempForms.push(formDynamicEntity);
    }
    return tempForms;
  }

  // 属性查询
  attributeSearch() {
    // 设置查询参数
    this.paras.type = this.node.type === '13' ? 'arcgis' : this.node.type === '23' ? 'geoserver' : 'geoserver';
    this.paras.baseUrl = this.node.url;
    this.paras.layerName = this.node.groupname;
    this.paras.geometryField = this.node.geoField;
    this.paras.inExtent = this.inExtent;
    this.paras.extent = this.inExtent === true ? form.ConfigService.map.getExtent() : {};

    // 根据显示数据量设置弹窗样式
    this.searchService.option.infoWindowHeight = this.showFields.length > 12 ? '280px' : 'unset';
    this.searchService.option.infoWindowOverflow = this.showFields.length > 12 ? 'scroll' : 'unset';
    document.getElementById('attribute-search-table-b').style.width = this.showFields.length > 12 ? 'unset' : '220px';

    // 开始查询
    this.searchService.attributeSearch(this.form.value, this.node.medname, this.paras);
  }

  // 清除动态表单属性值
  clearFormValue() {
    const formValues = this.form.value;
    const obj = {};
    if (formValues) {
      for (const key in formValues) {
        if (formValues.hasOwnProperty(key) === true) {
          obj[key] = null;
        }
      }
    }
    this.form.patchValue(obj);
  }


  /***
   * 重置查询
   */
  resetObject() {
    this.clearFormValue();
    this.searchService.reset();
  }

  // 重新初始化属性查询
  reInitAttributeService() {
    this.searchService.reInitAttributeService(this.paras.type, this.searchService.option);
  }

}
